//
//  HELCourseContentsVC.m
//  NursingAssociation
//
//  Created by wsj2015 on 2017/2/16.
//  Copyright © 2017年 wsj2015. All rights reserved.
//

#import "HELCourseContentsVC.h"
#import "HELCourseContentCell.h"
#import "Masonry.h"
#import "HELCourseContentModel.h"
#import "HELPrepareForExamVC.h"
//#import "TYVideoPlayerController.h"
#import "MoviePlayerViewController.h"
#import "ReaderFileViewController.h"

#import "HELService.h"
@interface HELCourseContentsVC ()

@property (nonatomic,  strong) UILabel *titleL;

@property (nonatomic,  assign) BOOL isFirstEnty;

@property (nonatomic,  strong) NSDictionary *examInor;

@property (nonatomic,  assign) BOOL canScroll;


@end

@implementation HELCourseContentsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isFirstEnty = NO;
    self.canScroll = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:kGoTopNotificationName object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:kLeaveTopNotificationName object:nil];//其中一个TAB离开顶部的时候，如果其他几个偏移量不为0的时候，要把他们都置为0
    weakSelf_define;
    [self.tableView wsj_HeaderRefreshBlock:^{
        [weakSelf reqestData];
    }];
}


- (void)acceptMsg:(NSNotification *)notification{
    
    NSString *notificationName = notification.name;
    if ([notificationName isEqualToString:kGoTopNotificationName]) {
        NSDictionary *userInfo = notification.userInfo;
        NSString *canScroll = userInfo[@"canScroll"];
        if ([canScroll isEqualToString:@"1"]) {
            self.canScroll = YES;
            self.tableView.showsVerticalScrollIndicator = YES;
        }
    }else if([notificationName isEqualToString:kLeaveTopNotificationName]){
        self.tableView.contentOffset = CGPointZero;
        self.canScroll = NO;
        self.tableView.showsVerticalScrollIndicator = NO;
    }

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (!self.canScroll) {
        [scrollView setContentOffset:CGPointZero];
        
    }
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY<0) {
        if (!self.isFirstEnty) {
            return;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kLeaveTopNotificationName object:nil userInfo:@{@"canScroll":@"1"}];
    }
}
- (void)configUI{
   
    UIView *div = [UIView new];
    div.backgroundColor = [UIColor whiteColor];
    div.frame = CGRectMake(0, 0, kScreenWidth, 49);
    [self.view addSubview:div];
    self.titleL = [UILabel new];
    self.titleL.text = @"目录标题";
    self.titleL.numberOfLines = 2;
    self.titleL.frame = CGRectMake(0, 0, kScreenWidth, 44);
    self.titleL.font = [UIFont systemFontOfSize:16];
    self.titleL.textColor = [UIColor blackColor];
    self.titleL.textAlignment = NSTextAlignmentCenter;
    [div addSubview:self.titleL];
    UIView *line = [UIView new];
    line.frame = CGRectMake(0, 44, kScreenWidth, 5);
    line.backgroundColor = kTableView_bg;
    [div addSubview:line];
    
//    self.tableView.frame = CGRectMake(0, 49, kScreenWidth, self.view.bounds.size.height -49 - 49 - 64);
    [self.view addSubview:self.tableView];
    self.tableView.dataVerticalOffset = 70;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(div);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"HELCourseContentCell" bundle:nil] forCellReuseIdentifier:@"HELCourseContentCell"];

    NoficationCenter_Obeserve(reqestData, RefreshCourseContent);
    
    
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    CGRect frame =   self.tableView.frame;
    frame.size.height -= 64 + 49;
    self.tableView.frame = frame;
    
}

- (void)firstGetData{
    if (!self.isFirstEnty) {
        [self.tableView.header beginRefreshing];
        self.isFirstEnty = !self.isFirstEnty;
    }
  
   
    
}
- (void)reqestData{
  
    
    self.tableView.loading = YES;
    NSString *url =[NSString stringWithFormat:@"%@/%@",kCourseContent,self.courseDetail.id];
    weakSelf_define;
    [[HELNetworkManager sharedMg] GET:url parameters:nil success:^(id responseObject) {
        weakSelf.tableView.loading =NO;
        [weakSelf.tableView.header endRefreshing];
    
        [weakSelf.dataArray removeAllObjects];
        [weakSelf.dataArray addObjectsFromArray:[HELCourseContentModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"courseFileInfo"]]];
        if (responseObject[@"data"][@"examInfo"] &&![responseObject[@"data"][@"examInfo"] isKindOfClass:[NSNull class]]) {
            weakSelf.examInor =responseObject[@"data"][@"examInfo"];
        }
        [weakSelf.tableView reloadData];
    } failure:^(NSString *err) {
        weakSelf.tableView.loading =NO;
        [weakSelf.tableView.header endRefreshing];
    }];
    
    
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.examInor) {
        return self.dataArray.count  + 1;
    }else{
        return self.dataArray.count;
    }
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HELCourseContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HELCourseContentCell"];
    if (indexPath.row ==self.dataArray.count) {
        cell.examInfor = self.examInor?self.examInor:nil;
    }else{
        cell.model = self.dataArray[indexPath.row];
    }
    
    
    if (indexPath.row == self.dataArray.count) {
        //进入考试
        
        if ([self.courseDetail.status containsString:@"未参加"]) {
            cell.isAble = NO;
            
        }else{
            cell.isAble  =YES;
        }
      
    }else{
        
        HELCourseContentModel *model =self.dataArray[indexPath.row];
        
        if ([self.courseDetail.status containsString:@"未参加"] &&[model.isLook integerValue] == 0) {
            cell.isAble = NO;
            
        }else{
            cell.isAble  =YES;
        }

    }

 
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    
    if (indexPath.row == self.dataArray.count) {
        //进入考试
        
        if ([self.courseDetail.status containsString:@"未参加"]) {
            cwqAlertMessage(@"您还未参加课程学~");
             return;
        }
        HELPrepareForExamVC *vc =[[HELPrepareForExamVC alloc] initWithExamId:self.examInor[@"id"]];
        [self.parentViewController.navigationController pushViewController:vc animated:YES];
    }else{
        
        HELCourseContentModel *model =self.dataArray[indexPath.row];
    
        if ([self.courseDetail.status containsString:@"未参加"] &&[model.isLook integerValue] == 0) {
             cwqAlertMessage(@"不可以试看~");
            return;
        }
        

        if ([model.type integerValue] == 1) {
            
            
            MoviePlayerViewController *vc =[MoviePlayerViewController new];
            
            vc.videoURL = [NSURL URLWithString:model.fileUrl];
            
            //视屏
//            TYVideoPlayerController *playerController = [[TYVideoPlayerController alloc]init];
//            playerController.videoTitle = @"";
         
            //
            weakSelf_define;
            __block NSDate *date =[NSDate date];
            vc.didDismissBLock = ^(){
//                [weakSelf uploadVedioProgress:date withContent:model];
                [HELService uploadVedioProgress:date withcourseId:[weakSelf.courseDetail.id integerValue] withContentId:[model.id integerValue] couserStatus:weakSelf.courseDetail.status withContent:[model.isLook integerValue]];
                NoficationCenter_post(RefreshCourseDetail);
                  
            };
          
     
            
            [self presentViewController:vc animated:YES completion:nil];
        }else if ([model.type integerValue] == 2){
            //PDF
            ReaderFileViewController *fileViewController = [[ReaderFileViewController alloc] init];
            //
            //
            fileViewController.title = model.fileName;
            
            fileViewController.pdfModel = model;
            
            fileViewController.modalPresentationStyle = UIModalPresentationFullScreen;
            defineWeakSelf;
            fileViewController.callBack = ^(NSUInteger maxPage){
//                [weakSelf uploadPdfProgress:maxPage withContent:model];
                [HELService uploadPdfPage:maxPage withcourseId:[weakSelf.courseDetail.id integerValue]  withContentId:[model.id integerValue] couserStatus:weakSelf.courseDetail.status  withContent:[model.isLook integerValue]];
                NoficationCenter_post(RefreshCourseDetail);
            };
           
            [self presentViewController:fileViewController animated:YES completion:NULL];
            

            
            
        }
 
    }
    
    
}



@end
